/*
 * @FilePath: \flutter_ducafecat_news_getx\lib\common\widgets\app.dart
 * @Date: 2022-07-11 14:53:48
 * @LastEditTime: 2022-07-14 08:05:43
 * @Description: 
 */
import 'package:flutter/material.dart';
import 'package:flutter_ducafecat_news_getx/common/utils/iconfont.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_ducafecat_news_getx/common/values/values.dart';

/// 透明背景 AppBar
AppBar transparentAppBar({
  Widget? title,
  Widget? leading,
  List<Widget>? actions,
}) {
  return AppBar(
    // backgroundColor: Colors.transparent,//透明背景
    backgroundColor: Color.fromARGB(255, 230, 230, 230),
    elevation: 0,
    title: title,
    leading: leading,
    actions: actions,
  );
}

class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(10.w, 40.h, 10.w, 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Icon(Icons.menu),
          Container(
            height: 40.h,
            width: 300.w,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(20.h)),
                color: AppColors.primaryBackground),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.search_outlined),
                  Text('Faded Alan Walker')
                ],
              ),
            ),
          ),
          Icon(Iconfont.changge)
        ],
      ),
    );
  }

  @override
  Size get preferredSize => Size(100, 100);
}

/// 10像素 Divider
Widget divider10Px({Color bgColor = AppColors.secondaryElement}) {
  return Container(
    height: 10.w,
    decoration: BoxDecoration(
      color: bgColor,
    ),
  );
}

///带搜索框的AppBar
class SearchAppBar extends StatefulWidget implements PreferredSizeWidget {
  SearchAppBar({
    Key? key,
    this.borderRadius = 20,
    this.autoFocus = false,
    this.focusNode,
    this.controller,
    this.height = 40,
    this.value,
    this.leading,
    this.backgroundColor,
    this.suffix,
    this.actions = const [],
    this.hintText,
    this.onTap,
    this.onClear,
    this.onCancel,
    this.onChanged,
    this.onSearch,
    this.onRightTap,
  }) : super(key: key);
  //圆角弧度
  final double? borderRadius;
  //自动获取焦点
  final bool? autoFocus;
  final FocusNode? focusNode;
  //文本控制器
  final TextEditingController? controller;

  // 输入框高度 默认40
  final double height;

  // 默认值
  final String? value;

  // 最前面的组件
  final Widget? leading;

  // 背景色
  final Color? backgroundColor;

  // 搜索框内部后缀组件
  final Widget? suffix;

  // 搜索框右侧组件
  final List<Widget> actions;

  // 输入框提示文字
  final String? hintText;

  // 输入框点击回调
  final VoidCallback? onTap;

  // 清除输入框内容回调
  final VoidCallback? onClear;

  // 清除输入框内容并取消输入
  final VoidCallback? onCancel;

  // 输入框内容改变
  final ValueChanged<String>? onChanged;

  // 点击键盘搜索
  final ValueChanged<String>? onSearch;

  // 点击右边widget
  final VoidCallback? onRightTap;

  @override
  _SearchAppBar createState() => _SearchAppBar();

  @override
  Size get preferredSize => Size.fromHeight(height.h);
}

class _SearchAppBar extends State<SearchAppBar> {
  TextEditingController? _controller;
  FocusNode? _focusNode;

  bool get isFocus => _focusNode?.hasFocus ?? false; //是否获取焦点

  bool get isTextEmpty => _controller?.text.isEmpty ?? false; //输入框是否为空

  bool get isActionEmpty => widget.actions.isEmpty; // 右边布局是否为空

  bool isShowCancel = false;

  @override
  void initState() {
    _controller = widget.controller ?? TextEditingController();
    _focusNode = widget.focusNode ?? FocusNode();
    if (widget.value != null) _controller?.text = widget.value ?? "";
    // 焦点获取失去监听
    _focusNode?.addListener(() => setState(() {}));
    // 文本输入监听
    _controller?.addListener(() {
      setState(() {});
    });
    super.initState();
  }

  // 清除输入框内容
  void _onClearInput() {
    setState(() {
      _controller?.clear();
    });
    widget.onClear?.call();
  }

  // 取消输入框编辑失去焦点
  void _onCancelInput() {
    setState(() {
      _controller?.clear();
      _focusNode?.unfocus(); //失去焦点
    });
    // 执行onCancel
    widget.onCancel?.call();
  }

  List<Widget> _actions() {
    List<Widget> list = [];
    if (isFocus || !isTextEmpty) {
      list.add(InkWell(
        onTap: widget.onRightTap ?? _onCancelInput,
        child: Container(
          constraints: BoxConstraints(minWidth: 48.w),
          alignment: Alignment.center,
          child: Text('搜索',
              style: TextStyle(
                color: AppColors.primaryText,
                fontSize: 14.sp,
              )),
        ),
      ));
    } else if (!isActionEmpty) {
      list.addAll(widget.actions);
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return AppBar(
      backgroundColor: widget.backgroundColor,
      //阴影z轴
      elevation: 0,
      // 标题与其他控件的间隔
      titleSpacing: 0,
      leadingWidth: 40.w,
      leading: widget.leading ??
          InkWell(
            child: Icon(
              Icons.menu,
              color: AppColors.primaryText,
              size: 18.sp,
            ),
            onTap: () {},
          ),
      title: Container(
          margin: EdgeInsetsDirectional.only(end: 10.w),
          height: widget.height,
          decoration: BoxDecoration(
            color: Color(0xFFF2F2F2),
            borderRadius: BorderRadius.circular(widget.borderRadius!.w),
          ),
          child: Container(
            child: Row(
              children: [
                SizedBox(
                  width: widget.height,
                  height: widget.height,
                  child:
                      Icon(Icons.search, size: 20.w, color: Color(0xFF999999)),
                ),
                Expanded(
                  // 权重
                  flex: 1,
                  child: TextField(
                    autofocus: widget.autoFocus ?? false,
                    // 是否自动获取焦点
                    focusNode: _focusNode,
                    // 焦点控制
                    controller: _controller,
                    // 与输入框交互控制器
                    //装饰
                    decoration: InputDecoration(
                      isDense: true,
                      border: InputBorder.none,
                      hintText: widget.hintText ?? '请输入关键字',
                      hintStyle: TextStyle(
                          fontSize: 14.sp, color: AppColors.primaryText),
                    ),
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: AppColors.primaryText,
                    ),
                    // 键盘动作右下角图标
                    textInputAction: TextInputAction.search,
                    onTap: widget.onTap,
                    // 输入框内容改变回调
                    onChanged: widget.onChanged,
                    onSubmitted: widget.onSearch, //输入框完成触发
                  ),
                ),
              ],
            ),
          )),
      actions: _actions(),
    );
  }

  @override
  void dispose() {
    _controller?.dispose();
    _focusNode?.dispose();
    super.dispose();
  }
}
